package com.triones.yjj.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.event.Order;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.imgconflate.PosterQrcodeUtil;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SnCreator;
import com.ruoyi.system.domain.SysRoleMenu;
import com.ruoyi.system.mapper.SysUserMapper;
import com.triones.biz.infra.entity.file.vo.FileVO;
import com.triones.biz.infra.service.file.FileService;
import com.triones.yjj.entity.*;
import com.triones.yjj.entity.bo.*;
import com.triones.yjj.entity.vo.*;
import com.triones.yjj.mapper.*;
import com.triones.yjj.service.ActivityService;
import com.triones.yjj.service.MemberDistributionRecordService;
import com.triones.yjj.service.QrService;
import com.triones.yjj.service.WeChatManager;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.formula.functions.T;
import org.checkerframework.checker.units.qual.C;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 活动管理 service 业务实现
 *
 * @Author: triones
 */
@Service
@RequiredArgsConstructor
public class ActivityServiceImpl implements ActivityService {

    private final ActivityMapper activityMapper;

    private final StaffMapper staffMapper;

    private final StaffActivityRelateMapper staffActivityRelateMapper;

    private final GroupPurchaseGoodsMapper groupPurchaseGoodsMapper;

    private final GroupPurchaseGoodsItemMapper groupPurchaseGoodsItemMapper;

    private final MemberBrowseMapper memberBrowseMapper;

    private final ShareMapper shareMapper;

    private final OrderMapper orderMapper;

    private final MemberDistributionRecordMapper memberDistributionRecordMapper;

    private final MemberGroupPurchaseMapper memberGroupPurchaseMapper;

    private final MemberGroupPurchaseItemMapper memberGroupPurchaseItemMapper;

    private final RefundTradeMapper refundTradeMapper;

    private final ActivityPrizeMapper activityPrizeMapper;

    private final InviteRewardMapper inviteRewardMapper;

    private final ShareRecordMapper shareRecordMapper;

    private final WeChatManager weChatManager;

    private final MemberMapper memberMapper;

    private final FileService fileService;

    private final QrService qrService;

    private final MemberActivityRelateMapper memberActivityRelateMapper;

    private final SysUserMapper baseMapper;

    private final OrderTradeRecordMapper orderTradeRecordMapper;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public List<ActivityVO> getList(ActivityListParams params) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<ActivityDO> wrapper = Wrappers.query();
        wrapper.eq("a.user_id",loginUser.getUserId());
        wrapper.eq(ObjectUtil.isNotNull(params.getMemberId()),"b.member_id",params.getMemberId());
        wrapper.eq(ObjectUtil.isNull(params.getMemberId()),"a.deleted",0);
        wrapper.eq("a.is_draft",0);
        wrapper.groupBy("a.id");
        return activityMapper.getList(wrapper);
    }

    @Override
    public ActivityVO getDetailById(Long id) {
        return activityMapper.getDetailById(id);
    }

    @Override
    public TableDataInfo<VisitAuthActivityListVO> visitAuthActivityPageList(ActivityListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        params.setUserId(loginUser.getUserId());
        Page<VisitAuthActivityListVO> result = activityMapper.teamNoExistStaffPageList(pageQuery.build(),params);
        return TableDataInfo.build(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setAllStaffVisit(Long id) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        /**
         * 给活动设置是否所有员工可见
         */
        ActivityDO activityDO = activityMapper.selectById(id);
        if (activityDO == null) {
            throw new ServiceException("活动不存在");
        }
        activityDO.setIsAllStaffVisible(1);
        activityMapper.updateById(activityDO);
        /**
         * 删除关联
         */
        QueryWrapper<StaffActivityRelateDO> wrapper = Wrappers.query();
        wrapper.eq("activity_id",id);
        staffActivityRelateMapper.delete(wrapper);
        /**
         * 查询所有员工
         */
        LambdaQueryWrapper<StaffDO> lqw = Wrappers.lambdaQuery();
        lqw.eq(StaffDO::getUserId,loginUser.getUserId()).eq(StaffDO::getDeleted,0);
        List<StaffDO> staffDOS = staffMapper.selectList(lqw);
        if (staffDOS.size() > 0) {
            List<StaffActivityRelateDO> addList = new ArrayList<>();
            staffDOS.forEach(item -> {
                StaffActivityRelateDO staffActivityRelateDO = new StaffActivityRelateDO();
                staffActivityRelateDO.setActivityId(id);
                staffActivityRelateDO.setStaffId(item.getId());
                addList.add(staffActivityRelateDO);
            });
            if (addList.size() > 0) {
                staffActivityRelateMapper.insertBatch(addList);
            }
        }
        return true;
    }

    public ActivityWxInfoVO getActivityInfoById(Long id) {
        return activityMapper.getActivityInfoById(id);
    }
    public ActivityCountBSAVO getActivityCountBSATotal(Long id) {
        ActivityCountBSAVO activityCountBSAVO = activityMapper.getActivityCountBSATotal(id);
        if(ObjectUtil.isNotEmpty(activityCountBSAVO)){
            activityCountBSAVO.setUserList(activityMapper.getActivityBrowseUserList(id));
        }
        return activityCountBSAVO;
    }

    public List<ActivityOrderUserVO> getActivityOrderUserList(Long id) {
        return activityMapper.getActivityOrderUserList(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveActivity(ActivityDO dto) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        /**
         * 处理拼团商品
         */
        HashMap map = JSONUtil.toBean(dto.getContent(), HashMap.class);
        HashMap pintuanGoodsConfig = JSONUtil.toBean(map.get("pintuan_goods_config").toString(), HashMap.class);
        GroupPurchaseGoodsDO groupPurchaseGoodsDO = new GroupPurchaseGoodsDO();
        if (pintuanGoodsConfig != null) {
            HashMap welfareTitle = JSONUtil.toBean(pintuanGoodsConfig.get("welfare_title").toString(), HashMap.class);
            groupPurchaseGoodsDO.setGoodsName("商品一");
            groupPurchaseGoodsDO.setGoodsNo(SnCreator.getGoodsSn());
            groupPurchaseGoodsDO.setGoodsSubtitle(Convert.toStr(welfareTitle.get("subtitle"),null));
            groupPurchaseGoodsDO.setPrice(Convert.toBigDecimal(pintuanGoodsConfig.get("pintuan_price")));
            if (Convert.toBool(pintuanGoodsConfig.get("is_inventory"))) {
                groupPurchaseGoodsDO.setIsInventory(1);
                groupPurchaseGoodsDO.setInventoryNumber(Convert.toInt(pintuanGoodsConfig.get("inventory_number"),0));
            }
            groupPurchaseGoodsDO.setUserId(loginUser.getUserId());
            groupPurchaseGoodsMapper.insert(groupPurchaseGoodsDO);
            /**
             * 处理阶梯商品
             */
            List<HashMap> intervalGoodsList = JSONUtil.toList(Convert.toStr(pintuanGoodsConfig.get("interval_goods_list")),HashMap.class);
            for (HashMap hashMap : intervalGoodsList) {
                GroupPurchaseGoodsItemDO groupPurchaseGoodsItemDO = new GroupPurchaseGoodsItemDO();
                groupPurchaseGoodsItemDO.setGroupPurchaseGoodsId(groupPurchaseGoodsDO.getId());
                groupPurchaseGoodsItemDO.setWelfareName(Convert.toStr(hashMap.get("welfare_name")));
                groupPurchaseGoodsItemDO.setConstituteNumber(Convert.toInt(hashMap.get("constitute_number")));
                groupPurchaseGoodsItemDO.setUserId(loginUser.getUserId());
                groupPurchaseGoodsItemMapper.insert(groupPurchaseGoodsItemDO);
                hashMap.put("id",Convert.toStr(groupPurchaseGoodsItemDO.getId()));
            }
            pintuanGoodsConfig.put("interval_goods_list",JSONUtil.parse(intervalGoodsList));
            map.put("pintuan_goods_config",JSONUtil.parse(pintuanGoodsConfig));
        }
        /**
         * 处理奖品
         */
        HashMap inviteRewardConfig = JSONUtil.toBean(map.get("invite_reward_config").toString(), HashMap.class);
        List<Long> prizeIds = new ArrayList<>();
        if (inviteRewardConfig != null) {
            List<HashMap> prizeList = JSONUtil.toList(Convert.toStr(inviteRewardConfig.get("prize_list")),HashMap.class);
            for (HashMap hashMap : prizeList) {
                ActivityPrizeDO activityPrizeDO = new ActivityPrizeDO();
                activityPrizeDO.setTitle(Convert.toStr(hashMap.get("title")));
                activityPrizeDO.setCover(Convert.toStr(hashMap.get("cover")));
                activityPrizeDO.setPrice(Convert.toBigDecimal(hashMap.get("price")));
                activityPrizeDO.setRequirementInviteNumber(Convert.toInt(hashMap.get("requirement_invite_number")));
                if (Convert.toBool(hashMap.get("is_inventory"))) {
                    activityPrizeDO.setIsInventory(1);
                    activityPrizeDO.setInventory(Convert.toInt(hashMap.get("inventory")));
                }
                activityPrizeDO.setUserId(loginUser.getUserId());
                activityPrizeMapper.insert(activityPrizeDO);
                hashMap.put("id",Convert.toStr(activityPrizeDO.getId()));
                prizeIds.add(activityPrizeDO.getId());
            }
            inviteRewardConfig.put("prize_list",JSONUtil.parse(prizeList));
            map.put("invite_reward_config",JSONUtil.parse(inviteRewardConfig));
        }
        /**
         * 处理封面图
         */
        HashMap shareConfig = JSONUtil.toBean(map.get("share_config").toString(), HashMap.class);
        if (shareConfig != null) {
            dto.setCover(Convert.toStr(shareConfig.get("cover")));
        }
        /**
         * 计算状态
         */
        long createStamp = DateUtil.getDateline();
        try {
            long startStamp = DateUtil.getDateline(dto.getStartTime(),"yyyy-MM-dd HH:mm:ss");
            long endStamp = DateUtil.getDateline(dto.getEndTime(),"yyyy-MM-dd HH:mm:ss");
            //0未开始1进行中2已结束
            if (createStamp < startStamp) {
                dto.setState(0);
            } else if (createStamp >= startStamp && createStamp <= endStamp) {
                dto.setState(1);
            } else {
                dto.setState(2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("活动时间不能为空");
        }
        dto.setContent(JSONUtil.toJsonStr(map));
        dto.setTypeId(1L);
        dto.setGroupPurchaseGoodsId(groupPurchaseGoodsDO.getId());
        dto.setUserId(loginUser.getUserId());
        dto.setIsAllStaffVisible(1);
        activityMapper.insert(dto);

        /**
         * 修改活动奖品信息
         */
        if (prizeIds.size() > 0) {
            List<ActivityPrizeDO> prizeDOS = activityPrizeMapper.selectList(new LambdaQueryWrapper<ActivityPrizeDO>().in(ActivityPrizeDO::getId, prizeIds));
            if (prizeDOS != null && prizeDOS.size() > 0) {
                prizeDOS.forEach(item -> {
                    item.setActivityId(dto.getId());
                });
            }
            activityPrizeMapper.updateBatchById(prizeDOS);
        }

        /**
         * 所有员工都有权限
         */
        LambdaQueryWrapper<StaffDO> lqw = Wrappers.lambdaQuery();
        lqw.eq(StaffDO::getUserId,loginUser.getUserId()).eq(StaffDO::getDeleted,0);
        List<StaffDO> staffDOS = staffMapper.selectList(lqw);
        if (staffDOS.size() > 0) {
            List<StaffActivityRelateDO> addList = new ArrayList<>();
            staffDOS.forEach(item -> {
                StaffActivityRelateDO staffActivityRelateDO = new StaffActivityRelateDO();
                staffActivityRelateDO.setActivityId(dto.getId());
                staffActivityRelateDO.setStaffId(item.getId());
                addList.add(staffActivityRelateDO);
            });
            if (addList.size() > 0) {
                staffActivityRelateMapper.insertBatch(addList);
            }
        }
        return true;
    }

    @Override
    public TableDataInfo<ActivityListVO> pageList(ActivityListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<ActivityDO> wrapper = Wrappers.query();
        wrapper.like(ObjectUtil.isNotEmpty(params.getTitle()),"ta.title",params.getTitle());
        wrapper.eq(ObjectUtil.isNotNull(params.getState()),"ta.state",params.getState());
        wrapper.eq("ta.user_id",loginUser.getUserId());
        wrapper.eq("ta.is_draft",0);
        wrapper.eq("ta.deleted",0);
        wrapper.orderByDesc("ta.create_time");
        Page<ActivityListVO> result =  activityMapper.pageList(pageQuery.build(),wrapper);
        if (result != null && result.getRecords().size() > 0) {
            result.getRecords().forEach(item -> {

                HashMap contentMap = JSONUtil.toBean(item.getContent(), HashMap.class);
                if (contentMap != null) {
                    HashMap posterConfigMap = JSONUtil.toBean(Convert.toStr(contentMap.get("pintuan_goods_config")), HashMap.class);
                    if (posterConfigMap != null) {
                        HashMap custom = JSONUtil.toBean(Convert.toStr(posterConfigMap.get("custom")), HashMap.class);
                        if (custom != null) {
                            item.setIsOptionalIdentity(Convert.toBool(custom.get("is_optional_identity"),false));
                        }
                    }
                }


                item.setBrowseCount(this.browseCountNumber(item.getId()));
                item.setShareCount(this.shareCountNumber(item.getId()));
                List<OrderDO> dos = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
                    .eq(OrderDO::getActivityId, item.getId()).in(OrderDO::getStatus, 2,5));

                if (dos != null && dos.size() > 0) {
                    item.setBuyCount(dos.size());
                    item.setPayAmountTotal(dos.stream().map(OrderDO::getRealityPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                    item.setActualAmountTotal(dos.stream().map(OrderDO::getActualAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                    if (item.getIsOptionalIdentity()) {
                        item.setNewMemberOrderCount(Convert.toInt(dos.stream().filter(obj -> (ObjectUtil.isNotEmpty(obj.getOptionalIdentity()) && "new_member".equals(obj.getOptionalIdentity()))).count(),0));
                        item.setOldMemberOrderCount(Convert.toInt(dos.stream().filter(obj -> (ObjectUtil.isNotEmpty(obj.getOptionalIdentity()) && "old_member".equals(obj.getOptionalIdentity()))).count(),0));
                    }
                } else {
                    item.setNewMemberOrderCount(0);
                    item.setOldMemberOrderCount(0);
                    item.setBuyCount(0);
                    item.setPayAmountTotal(BigDecimal.ZERO);
                    item.setActualAmountTotal(BigDecimal.ZERO);
                }

                List<MemberDistributionRecordDO> distributionRecordDOS = memberDistributionRecordMapper.selectList(new LambdaQueryWrapper<MemberDistributionRecordDO>()
                    .eq(MemberDistributionRecordDO::getActivityId, item.getId()));
                if (distributionRecordDOS != null && distributionRecordDOS.size() > 0) {
                    item.setDistributionAmountTotal(distributionRecordDOS.stream().map(MemberDistributionRecordDO::getKickback).reduce(BigDecimal.ZERO, BigDecimal::add));
                } else {
                    item.setDistributionAmountTotal(BigDecimal.ZERO);
                }
                Map purchaseTotalByStatus = this.getGroupPurchaseTotalByStatus(item.getId());
                item.setReachCount(Convert.toInt(purchaseTotalByStatus.get("reachCount")));
                item.setFillCount(Convert.toInt(purchaseTotalByStatus.get("fillCount")));
                item.setNotPayHaveMobile(this.getNotPayHaveMobile(item.getId()));

                int achieveTeamCount = activityMapper.achieveTeamCount(item.getId());
                item.setAchieveTeamCount(achieveTeamCount);
                //成团数（指团人数在两人以上）
            });
        }
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<StaffActivityListVO> getStaffActivityPageList(WxStaffDetailVO params, PageQuery pageQuery) {
        QueryWrapper<ActivityDO> wrapper = Wrappers.query();
        wrapper.eq("sar.staff_id",params.getId());
        wrapper.eq("ta.deleted",0);
        wrapper.eq("ta.is_draft",0);
        wrapper.eq("ta.user_id",params.getUserId());
        wrapper.orderByDesc("ta.create_time");
        Page<StaffActivityListVO> result =  activityMapper.getStaffActivityPageList(pageQuery.build(),wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public Map activityDetailStats(Long id) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        Map map = new HashMap();
        /**
         * 浏览人数
         */
        Integer browseCount = this.browseCountNumber(id);
        map.put("browseCount",browseCount);
        /**
         * 分享人数
         */
        Integer shareCount = this.shareCountNumber(id);
        map.put("shareCount",shareCount);
        /**
         * 付款人数(成功报名量)、支付总额、分佣金额、微信实收手续费、实收总额、已结算金额、待结算实收解金额、已发佣金、已发奖励
         */
        List<OrderDO> dos = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
            .eq(OrderDO::getActivityId, id).in(OrderDO::getStatus, 2, 5));
        if (dos != null && dos.size() > 0) {
            map.put("buyCount",dos.size());
            BigDecimal payAmountTotal = dos.stream().filter(s -> ObjectUtil.isNotNull(s.getRealityPayAmount())).collect(Collectors.toList())
                .stream().map(OrderDO::getRealityPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            map.put("payAmountTotal",payAmountTotal);
            map.put("distributionAmountTotal",
                (dos.stream().filter(s -> ObjectUtil.isNotNull(s.getOneDistributionAmount())).collect(Collectors.toList())
                    .stream().map(OrderDO::getOneDistributionAmount).reduce(BigDecimal.ZERO, BigDecimal::add))
                    .add(dos.stream().filter(s -> ObjectUtil.isNotNull(s.getTwoDistributionAmount())).collect(Collectors.toList())
                        .stream().map(OrderDO::getTwoDistributionAmount).reduce(BigDecimal.ZERO, BigDecimal::add)));
            map.put("commissionTotal",(dos.stream().filter(s -> ObjectUtil.isNotNull(s.getCommission())).collect(Collectors.toList())
                .stream().map(OrderDO::getCommission).reduce(BigDecimal.ZERO, BigDecimal::add)));
            map.put("actualAmountTotal",
            (dos.stream().filter(s -> ObjectUtil.isNotNull(s.getActualAmount())).collect(Collectors.toList())
                .stream().map(OrderDO::getActualAmount).reduce(BigDecimal.ZERO, BigDecimal::add)));
            map.put("settlementAmount",dos.stream().filter(s -> s.getSettlementStatus() == 2 && ObjectUtil.isNotNull(s.getRealityPayAmount())).collect(Collectors.toList())
                                                   .stream().map(OrderDO::getRealityPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            map.put("waitSettlementAmount",dos.stream().filter(s -> s.getSettlementStatus() == 1 && ObjectUtil.isNotNull(s.getRealityPayAmount())).collect(Collectors.toList())
                .stream().map(OrderDO::getRealityPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            map.put("rewardAmountTotal",
            (dos.stream().filter(s -> ObjectUtil.isNotNull(s.getStaffRewardAmount())).collect(Collectors.toList())
                .stream().map(OrderDO::getStaffRewardAmount).reduce(BigDecimal.ZERO, BigDecimal::add)));
        } else {
            map.put("buyCount",0);
            map.put("payAmountTotal",0);
            map.put("distributionAmountTotal",0);
            map.put("commissionTotal",0);
            map.put("actualAmountTotal",0);
            map.put("settlementAmount",0);
            map.put("waitSettlementAmount",0);
            map.put("rewardAmountTotal",0);
        }
        /**
         * 成团数、满团数
         */
        Map purchaseTotalByStatus = this.getGroupPurchaseTotalByStatus(id);
        map.put("reachCount",purchaseTotalByStatus.get("reachCount"));
//        map.put("fillCount",purchaseTotalByStatus.get("fillCount"));
        int achieveTeamCount = activityMapper.achieveTeamCount(id);
        map.put("fillCount",achieveTeamCount);
        /**
         * 退款人数、退款金额
         */
        List<RefundTradeVO> refundList = refundTradeMapper.refundList(id);
        if (refundList != null && refundList.size() > 0) {
            map.put("refundCount",refundList.size());
            map.put("refundAmountTotal",refundList.stream().map(RefundTradeVO::getRefundAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        } else {
            map.put("refundCount",0);
            map.put("refundAmountTotal",0);
        }
        /**
         * 团长免单金额
         */
        BigDecimal freeShipingTotal = this.getFreeShipingTotal(id);
        map.put("freeShipingTotal",Convert.toBigDecimal(freeShipingTotal,BigDecimal.ZERO));
        return map;
    }

    @Override
    public TableDataInfo<ActivityOrderListVO> activityOrderList(ActivityManageDetailParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        params.setUserId(loginUser.getUserId());
        if (params.getEnrollDateRange() != null && params.getEnrollDateRange().size() > 0) {
            params.setEnrollDateRangeStartTime(params.getEnrollDateRange().get(0));
            params.setEnrollDateRangeEndTime(params.getEnrollDateRange().get(1));
        }
        Page<ActivityOrderListVO> result =  activityMapper.getActivityOrderList(pageQuery.build(),params);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<ActivityOrderGroupPurchaseListVO> activityOrderGroupPurchaseList(ActivityManageDetailParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<ActivityDO> wrapper = Wrappers.query();
        wrapper.eq("tmgp.user_id",loginUser.getUserId());
        wrapper.eq("tmgp.activity_id",params.getActivityId());
        wrapper.notIn("tmgp.status",1,-1);

        wrapper.and(ObjectUtil.isNotEmpty(params.getWxKeyword()),qw -> {
            qw.like("twu.nickname",params.getWxKeyword()).or()
                .like("a.enroll_mobile",params.getEnrollKeyword()).or()
                .eq("twu.id",params.getWxKeyword());
        });

        wrapper.and(ObjectUtil.isNotEmpty(params.getEnrollKeyword()),qw -> {
            qw.like("o.enroll_name",params.getEnrollKeyword()).or()
                .like("o.enroll_mobile",params.getEnrollKeyword());
            });

        wrapper.like(ObjectUtil.isNotEmpty(params.getGoodsName()),"tgpgi.welfare_name",params.getGoodsName());
        wrapper.eq(ObjectUtil.isNotEmpty(params.getOptionalIdentity()),"o.optional_identity",params.getOptionalIdentity());
        wrapper.eq(ObjectUtil.isNotNull(params.getGroupStatus()) && params.getGroupStatus() != 0,"tmgp.status",params.getGroupStatus());
        wrapper.eq(ObjectUtil.isNotNull(params.getTeamNumber()),"tmgp.personnel_number",params.getTeamNumber());
        Page<ActivityOrderGroupPurchaseListVO> result = activityMapper.activityOrderGroupPurchaseList(pageQuery.build(),wrapper);
        if (result.getRecords() != null && result.getRecords().size() > 0) {
            for (ActivityOrderGroupPurchaseListVO record : result.getRecords()) {
                record.setItemList(memberGroupPurchaseItemMapper.getItemList(record.getId()));
            }
        }
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<RefundListVO> refundPageList(RefundListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<RefundTradeDO> wrapper = Wrappers.query();
        wrapper.eq("trt.user_id",loginUser.getUserId());
        wrapper.eq("o.user_id",loginUser.getUserId());
        wrapper.eq("o.user_id",loginUser.getUserId());
        wrapper.eq("o.activity_id",params.getActivityId());
        wrapper.like(ObjectUtil.isNotEmpty(params.getWxKeyword()),"twu.nickname",params.getWxKeyword()).or()
            .eq(ObjectUtil.isNotEmpty(params.getWxKeyword()),"twu.id",params.getWxKeyword());
        wrapper.like(ObjectUtil.isNotEmpty(params.getEnrollKeyword()),"o.enroll_name",params.getEnrollKeyword()).or()
            .like(ObjectUtil.isNotEmpty(params.getEnrollKeyword()),"o.enroll_mobile",params.getEnrollKeyword());
        wrapper.eq(ObjectUtil.isNotEmpty(params.getRefundType()),"trt.refund_type",params.getRefundType());
        if (params.getRefundDateRange() != null && params.getRefundDateRange().size() > 0) {
            wrapper.between("trt.refund_time",params.getRefundDateRange().get(0),params.getRefundDateRange().get(1));
        }
        wrapper.le(ObjectUtil.isNotNull(params.getIsDistribution())  && params.getIsDistribution() == 2,"o.one_distribution_amount", 0)
            .le(ObjectUtil.isNotNull(params.getIsDistribution()) && params.getIsDistribution() == 2,"o.two_distribution_amount", 0);
        wrapper.gt(ObjectUtil.isNotNull(params.getIsDistribution())  && params.getIsDistribution() == 1,"o.one_distribution_amount", 0).or()
            .gt(ObjectUtil.isNotNull(params.getIsDistribution()) && params.getIsDistribution() == 1,"o.two_distribution_amount", 0);
        wrapper.orderByDesc("trt.create_time");
        Page<RefundListVO> result =  refundTradeMapper.refundPageList(pageQuery.build(),wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<InviteRewardListVO> inviteRewardPageList(InviteRewardListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<MemberActivityRelateDO> wrapper = Wrappers.query();
        wrapper.eq("tmar.user_id",loginUser.getUserId());
        wrapper.eq("tmar.activity_id",params.getActivityId());
        wrapper.like(ObjectUtil.isNotEmpty(params.getWxKeyword()),"twu.nickname",params.getWxKeyword()).or()
            .eq(ObjectUtil.isNotEmpty(params.getWxKeyword()),"twu.id",params.getWxKeyword());
        wrapper.like(ObjectUtil.isNotEmpty(params.getEnrollKeyword()),"o.enroll_name",params.getEnrollKeyword()).or()
            .like(ObjectUtil.isNotEmpty(params.getEnrollKeyword()),"o.enroll_mobile",params.getEnrollKeyword());
        wrapper.in(ObjectUtil.isNotNull(params.getIsPay()) && params.getIsPay() == 1,"o.status",2,5);
        wrapper.notIn(ObjectUtil.isNotNull(params.getIsPay()) && params.getIsPay() == 2,"o.status",2,5);
        Page<InviteRewardListVO> result =  shareMapper.inviteRewardPageList(pageQuery.build(),wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public ActivityVO getInfoById(Long id) {
        return activityMapper.selectVoById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editActivity(ActivityDO dto) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        ActivityDO activityDO = activityMapper.selectById(dto.getId());
        if (activityDO == null) {
            throw new SecurityException("活动不存在");
        }
        activityDO.setTitle(dto.getTitle());
        activityDO.setIsDraft(dto.getIsDraft());
        activityDO.setCover(dto.getCover());
        activityDO.setStartTime(dto.getStartTime());
        activityDO.setEndTime(dto.getEndTime());
        /**
         * 处理拼团商品
         */
        HashMap map = JSONUtil.toBean(dto.getContent(), HashMap.class);
        GroupPurchaseGoodsDO purchaseGoodsDO = groupPurchaseGoodsMapper.selectById(activityDO.getGroupPurchaseGoodsId());
        HashMap pintuanGoodsConfig = JSONUtil.toBean(map.get("pintuan_goods_config").toString(), HashMap.class);
        if (pintuanGoodsConfig != null) {
            HashMap welfareTitle = JSONUtil.toBean(pintuanGoodsConfig.get("welfare_title").toString(), HashMap.class);
            if (purchaseGoodsDO != null) {
                purchaseGoodsDO.setGoodsSubtitle(Convert.toStr(welfareTitle.get("subtitle"),null));
                purchaseGoodsDO.setPrice(Convert.toBigDecimal(pintuanGoodsConfig.get("pintuan_price")));
                if (Convert.toBool(pintuanGoodsConfig.get("is_inventory"))) {
                    purchaseGoodsDO.setIsInventory(1);
                    purchaseGoodsDO.setInventoryNumber(Convert.toInt(pintuanGoodsConfig.get("inventory_number"),0));
                }
                groupPurchaseGoodsMapper.updateById(purchaseGoodsDO);
                /**
                 * 处理阶梯商品
                 */
                List<HashMap> intervalGoodsList = JSONUtil.toList(Convert.toStr(pintuanGoodsConfig.get("interval_goods_list")),HashMap.class);
                /**
                 * 删除移除的
                 */
                List<Long> purchaseGoodsItemIds = new ArrayList<>();
                for (HashMap hashMap : intervalGoodsList) {
                    if (Convert.toLong(hashMap.get("id"),0L) != null && Convert.toLong(hashMap.get("id"),0L) != 0) {
                        //旧的商品
                        purchaseGoodsItemIds.add(Convert.toLong(hashMap.get("id")));
                        GroupPurchaseGoodsItemDO groupPurchaseGoodsItemDO = groupPurchaseGoodsItemMapper.selectById(Convert.toLong(hashMap.get("id")));
                        groupPurchaseGoodsItemDO.setWelfareName(Convert.toStr(hashMap.get("welfare_name")));
                        groupPurchaseGoodsItemDO.setConstituteNumber(Convert.toInt(hashMap.get("constitute_number")));
                        groupPurchaseGoodsItemMapper.updateById(groupPurchaseGoodsItemDO);
                    } else {
                        // 新的商品
                        GroupPurchaseGoodsItemDO groupPurchaseGoodsItemDO = new GroupPurchaseGoodsItemDO();
                        groupPurchaseGoodsItemDO.setGroupPurchaseGoodsId(purchaseGoodsDO.getId());
                        groupPurchaseGoodsItemDO.setWelfareName(Convert.toStr(hashMap.get("welfare_name")));
                        groupPurchaseGoodsItemDO.setConstituteNumber(Convert.toInt(hashMap.get("constitute_number")));
                        groupPurchaseGoodsItemDO.setUserId(loginUser.getUserId());
                        groupPurchaseGoodsItemMapper.insert(groupPurchaseGoodsItemDO);
                        hashMap.put("id",Convert.toStr(groupPurchaseGoodsItemDO.getId()));
                        purchaseGoodsItemIds.add(groupPurchaseGoodsItemDO.getId());
                    }
                }
                /**
                 * 删除移除的
                 */
                groupPurchaseGoodsItemMapper.delete(new LambdaQueryWrapper<GroupPurchaseGoodsItemDO>()
                    .eq(GroupPurchaseGoodsItemDO::getGroupPurchaseGoodsId, purchaseGoodsDO.getId())
                    .notIn(GroupPurchaseGoodsItemDO::getId,purchaseGoodsItemIds));
                pintuanGoodsConfig.put("interval_goods_list",JSONUtil.parse(intervalGoodsList));
                map.put("pintuan_goods_config",JSONUtil.parse(pintuanGoodsConfig));
            }
        }
        /**
         * 处理奖品
         */
        HashMap inviteRewardConfig = JSONUtil.toBean(map.get("invite_reward_config").toString(), HashMap.class);
        List<Long> newAndOldPrizeIds = new ArrayList<>();
        List<Long> newPrizeIds = new ArrayList<>();
        if (inviteRewardConfig != null) {
            List<HashMap> prizeList = JSONUtil.toList(Convert.toStr(inviteRewardConfig.get("prize_list")),HashMap.class);
            for (HashMap hashMap : prizeList) {
                if (Convert.toLong(hashMap.get("id"),0L) != null && Convert.toLong(hashMap.get("id"),0L) != 0) {
                    // 旧的
                    ActivityPrizeDO activityPrizeDO = activityPrizeMapper.selectById(Convert.toLong(hashMap.get("id")));
                    activityPrizeDO.setTitle(Convert.toStr(hashMap.get("title")));
                    activityPrizeDO.setCover(Convert.toStr(hashMap.get("cover")));
                    activityPrizeDO.setPrice(Convert.toBigDecimal(hashMap.get("price")));
                    activityPrizeDO.setRequirementInviteNumber(Convert.toInt(hashMap.get("requirement_invite_number")));
                    if (Convert.toBool(hashMap.get("is_inventory"))) {
                        activityPrizeDO.setIsInventory(1);
                        activityPrizeDO.setInventory(Convert.toInt(hashMap.get("inventory")));
                    }
                    activityPrizeMapper.updateById(activityPrizeDO);
                    newAndOldPrizeIds.add(Convert.toLong(hashMap.get("id")));
                } else {
                    // 新的
                    ActivityPrizeDO activityPrizeDO = new ActivityPrizeDO();
                    activityPrizeDO.setTitle(Convert.toStr(hashMap.get("title")));
                    activityPrizeDO.setCover(Convert.toStr(hashMap.get("cover")));
                    activityPrizeDO.setPrice(Convert.toBigDecimal(hashMap.get("price")));
                    activityPrizeDO.setRequirementInviteNumber(Convert.toInt(hashMap.get("requirement_invite_number")));
                    if (Convert.toBool(hashMap.get("is_inventory"))) {
                        activityPrizeDO.setIsInventory(1);
                        activityPrizeDO.setInventory(Convert.toInt(hashMap.get("inventory")));
                    }
                    activityPrizeDO.setUserId(loginUser.getUserId());
                    activityPrizeMapper.insert(activityPrizeDO);
                    hashMap.put("id",Convert.toStr(activityPrizeDO.getId()));
                    newAndOldPrizeIds.add(activityPrizeDO.getId());
                    newPrizeIds.add(activityPrizeDO.getId());
                }
            }
            inviteRewardConfig.put("prize_list",JSONUtil.parse(prizeList));
            map.put("invite_reward_config",JSONUtil.parse(inviteRewardConfig));
        }
        /**
         * 处理封面图
         */
        HashMap shareConfig = JSONUtil.toBean(map.get("share_config").toString(), HashMap.class);
        if (shareConfig != null) {
            activityDO.setCover(Convert.toStr(shareConfig.get("cover")));
        }
        /**
         * 计算状态
         */
        long createStamp = DateUtil.getDateline();
        try {
            long startStamp = DateUtil.getDateline(dto.getStartTime(),"yyyy-MM-dd HH:mm:ss");
            long endStamp = DateUtil.getDateline(dto.getEndTime(),"yyyy-MM-dd HH:mm:ss");
            if (createStamp < startStamp) {
                activityDO.setState(0);
            } else if (createStamp >= startStamp && createStamp <= endStamp) {
                activityDO.setState(1);
            } else {
                activityDO.setState(2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("活动时间不能为空");
        }
        activityDO.setContent(JSONUtil.toJsonStr(map));
        activityMapper.updateById(activityDO);

        /**
         * 修改活动奖品信息
         */
        if (newPrizeIds.size() > 0) {
            List<ActivityPrizeDO> prizeDOS = activityPrizeMapper.selectList(new LambdaQueryWrapper<ActivityPrizeDO>().in(ActivityPrizeDO::getId, newPrizeIds));
            if (prizeDOS != null && prizeDOS.size() > 0) {
                prizeDOS.forEach(item -> {
                    item.setActivityId(activityDO.getId());
                });
            }
            activityPrizeMapper.updateBatchById(prizeDOS);
        }
        /**
         * 删除移除的
         */
        activityPrizeMapper.delete(new LambdaQueryWrapper<ActivityPrizeDO>()
            .eq(ActivityPrizeDO::getActivityId,activityDO.getId()).notIn(ActivityPrizeDO::getId,newAndOldPrizeIds));
        return true;
    }

    @Override
    public Boolean remove(Long id) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        ActivityDO activityDO = activityMapper.selectById(id);
        if (activityDO == null) {
            throw new SecurityException("活动不存在");
        }
        return activityMapper.deleteById(activityDO) > 0;
    }

    @Override
    public Boolean inviteRewardVerification(InviteRewardDO dto) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        InviteRewardDO inviteRewardDO = inviteRewardMapper.selectById(dto.getId());
        if (inviteRewardDO == null) {
            throw new SecurityException("邀请奖励记录不存在");
        }
        if (!inviteRewardDO.getVerificationCode().equals(dto.getVerificationCode())) {
            throw new SecurityException("核销码错误");
        }
        if (inviteRewardDO.getVerificationStatus() != 1) {
            throw new SecurityException("该记录已核销");
        }
        inviteRewardDO.setVerificationStatus(2);
        // -1表示主账号核销
        inviteRewardDO.setVerificationStaffId(-1L);
        inviteRewardDO.setVerificationTime(DateUtil.getDateTimeString());
        return inviteRewardMapper.updateById(inviteRewardDO) > 0;
    }

    /**
     * 获取浏览人数
     */
    public Integer browseCountNumber(Long activityId) {
        Integer number = 0;
        Long count = memberBrowseMapper.selectCount(new LambdaQueryWrapper<MemberBrowseDO>().eq(MemberBrowseDO::getProductId, activityId));
        number = Convert.toInt(count,0);
        return number;
    }

    /**
     * 获取分享人数
     */
    public Integer shareCountNumber(Long activityId) {
        Integer number = 0;
        Long count = shareMapper.selectCount(new LambdaQueryWrapper<ShareDO>().eq(ShareDO::getProductId,activityId));
        number = Convert.toInt(count,0);
        return number;
    }

    /**
     * 获取付款人数
     */
    public Integer buyNumber(Long activityId) {
        Integer number = 0;
        Long count = orderMapper.selectCount(new LambdaQueryWrapper<OrderDO>()
            .eq(OrderDO::getActivityId,activityId).in(OrderDO::getStatus,2,5));
        number = Convert.toInt(count,0);
        return number;
    }

    /**
     * 获取付款人数 和 付款总金额
     */
    public Map realityPayAmountTotalAndBuyNumber(Long activityId) {
        Map map = new HashMap();
        Integer number = 0;
        BigDecimal total = BigDecimal.ZERO;
        List<OrderDO> dos = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
            .eq(OrderDO::getActivityId, activityId).in(OrderDO::getStatus, 2, 5));
        if (dos != null && dos.size() > 0) {
            total = dos.stream().map(OrderDO::getRealityPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        }
        map.put("number",number);
        map.put("total",total);
        return map;
    }

    /**
     * 获取成团数 和 满团数
     */
    public Map getGroupPurchaseTotalByStatus(Long activityId) {
        Map map = new HashMap();
        Integer reachNumber = 0;
        Integer fillNumber = 0;
        List<MemberGroupPurchaseDO> dos = memberGroupPurchaseMapper.selectList(new LambdaQueryWrapper<MemberGroupPurchaseDO>()
            .eq(MemberGroupPurchaseDO::getActivityId, activityId));
        if (dos != null && dos.size() > 0) {
            for (MemberGroupPurchaseDO aDo : dos) {
                if (aDo.getStatus() == 2) {
                    reachNumber ++;
                }
                if (aDo.getStatus() == 3) {
                    fillNumber++;
                }
            }
        }
        map.put("reachCount",reachNumber);
        map.put("fillCount",fillNumber);
        return map;
    }

    /**
     * 获取免单金额总和
     */
    public BigDecimal getFreeShipingTotal(Long activityId) {
        BigDecimal total = BigDecimal.ZERO;
        total = memberGroupPurchaseItemMapper.getFreeShipingTotal(activityId);
        return total;
    }

    @Override
    public ActivityVO getStaffNewActivity(Long staffId,Long userId) {
        return activityMapper.getStaffNewActivity(staffId,userId);
    }

    public ActivityVO selectVoById(Long id) {
        return activityMapper.selectVoById(id);
    }

    @Override
    public TableDataInfo<ActivityListVO> draftPageList(PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<ActivityDO> wrapper = Wrappers.query();
        wrapper.eq("ta.user_id",loginUser.getUserId());
        wrapper.eq("ta.deleted",0);
        wrapper.eq("ta.is_draft",1);
        wrapper.orderByDesc("ta.update_time");
        Page<ActivityListVO> result =  activityMapper.pageList(pageQuery.build(),wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<CanMoveTeamVO> canMoveTeamPageList(CanMoveTeamParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<MemberGroupPurchaseDO> wrapper = Wrappers.query();
        wrapper.eq("tmgp.activity_id",params.getActivityId());
        wrapper.eq("tmgp.user_id",loginUser.getUserId());
        wrapper.ne("tmgp.id",params.getGroupPurchaseId());
        wrapper.notIn("tmgp.status",-1);
        wrapper.gt("tmgp.personnel_number",0);
        if (ObjectUtil.isNotEmpty(params.getKeyword())) {
            wrapper.like("twu.nickname",params.getKeyword()).or()
                .like("tmgpi.register_name",params.getKeyword()).or()
                .like("tmgpi.register_mobile",params.getKeyword()).or();
        }
        Page<CanMoveTeamVO> result = memberGroupPurchaseMapper.canMoveTeamPageList(pageQuery.build(),wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public Map activityBigData(Long activityId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        ActivityVO activityVO = activityMapper.selectVoById(activityId);
        if (activityVO == null) {
            throw new ServiceException("活动不存在");
        }
        Map map = new HashMap();
        List<BigDataEnrollListVO> enrollLists = new ArrayList();
        map.put("title",activityVO.getTitle());
        map.put("startTime",activityVO.getStartTime());
        map.put("endTime",activityVO.getEndTime());

        // 获取是否开启 新生老生
        HashMap contentMap = JSONUtil.toBean(activityVO.getContent(), HashMap.class);
        map.put("isShowStudent",false);
        if (contentMap != null) {
            HashMap posterConfigMap = JSONUtil.toBean(Convert.toStr(contentMap.get("pintuan_goods_config")), HashMap.class);
            if (posterConfigMap != null) {
                HashMap custom = JSONUtil.toBean(Convert.toStr(posterConfigMap.get("custom")), HashMap.class);
                if (custom != null) {
                    if (Convert.toBool(custom.get("is_optional_identity"),false)) {
                        map.put("isShowStudent",true);
                        //查询新老生数量
                        long oldStudent = orderMapper.selectCount(new LambdaQueryWrapper<OrderDO>().eq(OrderDO::getOptionalIdentity, "old_member")
                            .eq(OrderDO::getActivityId,activityId)
                            .in(OrderDO::getStatus, 2, 5));
                        map.put("oldStudent",Convert.toInt(oldStudent));
                        long newStudent = orderMapper.selectCount(new LambdaQueryWrapper<OrderDO>().eq(OrderDO::getOptionalIdentity, "new_member")
                            .eq(OrderDO::getActivityId,activityId)
                            .in(OrderDO::getStatus, 2, 5));
                        map.put("newStudent",Convert.toInt(newStudent));

                    }
                }
            }
        }
        //有效报名列表 以及 数量
        enrollLists = activityMapper.getBigDataEnrollList(activityId);
        map.put("enrollList",enrollLists);
        if (enrollLists != null && enrollLists.size() > 0) {
            if (enrollLists.size() < 10) {
                map.put("enrollNumber","0" + enrollLists.size());
            } else {
                map.put("enrollNumber",enrollLists.size());
            }
            map.put("orderNumber",enrollLists.size());
        } else {
            map.put("enrollNumber","00");
            map.put("orderNumber",0);
        }

        /**
         * 明星员工榜
         */
        List<Map> staffRank = activityMapper.getStaffRank(activityId);
        map.put("staffRank",staffRank);

        /**
         * 浏览次数,浏览人数
         */
        List<MemberBrowseDO> browseDOS = memberBrowseMapper.selectList(new LambdaQueryWrapper<MemberBrowseDO>().eq(MemberBrowseDO::getProductId, activityId));
        if (browseDOS != null && browseDOS.size() > 0) {
            int sum = Convert.toInt(browseDOS.stream().mapToLong(MemberBrowseDO::getBrowseNumber).sum(),0);
            map.put("browseNumber",sum);
            map.put("personBrowseNumber",browseDOS.size());
        } else {
            map.put("browseNumber",0);
            map.put("personBrowseNumber",0);
        }

        /**
         * 分享次数
         */
        List<ShareDO> shareDOS = shareMapper.selectList(new LambdaQueryWrapper<ShareDO>().eq(ShareDO::getProductId, activityId));
        if (shareDOS != null && shareDOS.size() > 0) {
            int sum = Convert.toInt(shareDOS.stream().mapToLong(ShareDO::getShareNumber).sum(),0);
            map.put("shareNumber",sum);
        } else {
            map.put("shareNumber",0);
        }
        /**
         * 组织当前六小时
         */
        List<String> sixHours = new ArrayList<>();
        sixHours.add(Convert.toInt(DateFormatUtils.format(cn.hutool.core.date.DateUtil.offset(new Date(), DateField.HOUR, -5), "HH")) + ":00");
        sixHours.add(Convert.toInt(DateFormatUtils.format(cn.hutool.core.date.DateUtil.offset(new Date(), DateField.HOUR, -4), "HH")) + ":00");
        sixHours.add(Convert.toInt(DateFormatUtils.format(cn.hutool.core.date.DateUtil.offset(new Date(), DateField.HOUR, -3), "HH")) + ":00");
        sixHours.add(Convert.toInt(DateFormatUtils.format(cn.hutool.core.date.DateUtil.offset(new Date(), DateField.HOUR, -2), "HH")) + ":00");
        sixHours.add(Convert.toInt(DateFormatUtils.format(cn.hutool.core.date.DateUtil.offset(new Date(), DateField.HOUR, -1), "HH")) + ":00");
        sixHours.add(Convert.toInt(DateFormatUtils.format(cn.hutool.core.date.DateUtil.offset(new Date(), DateField.HOUR, 0), "HH")) + ":00");
        map.put("sixHours",sixHours);

        /**
         * 获取当前6小时的浏览次数
         */
        List<Integer> sixHoursBrowseNumber = shareRecordMapper.theFirstSixHours(activityId);
        map.put("sixHoursBrowseNumber",sixHoursBrowseNumber);

        /**
         * 获取当前6小时的浏览人数
         */
        List<Integer> sixHoursPersonBrowseNumber = shareMapper.theFirstSixHours(activityId);
        map.put("sixHoursPersonBrowseNumber",sixHoursPersonBrowseNumber);

        /**
         * 员工排名
         */
        List<StaffRankListVO> staffRankList = staffMapper.staffRankList(activityId,loginUser.getUserId());
        map.put("staffRankList",staffRankList);
        /**
         * 战队排名
         */
        List<StaffRankListVO> staffRankTeamList = staffMapper.teamStatsList(activityId,loginUser.getUserId());
        map.put("staffRankTeamList",staffRankTeamList);
        return map;
    }

    @Override
    public Map getWxSubscribeToUrl(String query) {
        Map map = new HashMap();
        String path = "pages/index/index";
        String urlLink = weChatManager.generateUrlLink(path, query);
        map.put("urlLink",urlLink);
        return map;
    }

    @Override
    public Map getPosterConfig(Long activityId) {
        Map map = new HashMap();
        ActivityVO activityVO = activityMapper.selectVoById(activityId);
        if (activityVO != null) {
            HashMap contentMap = JSONUtil.toBean(activityVO.getContent(), HashMap.class);
            if (contentMap != null) {
                map.put("poster_config",Convert.toStr(contentMap.get("poster_config"),null));
            }
        }
        return map;
    }

    @Override
    public Boolean updatePosterConfig(PosterConfigBO bo) {
        ActivityDO activityDO = activityMapper.selectById(bo.getActivityId());
        if (activityDO == null) {
            throw new ServiceException("活动不存在");
        }
        HashMap map = JSONUtil.toBean(activityDO.getContent(), HashMap.class);
        map.put("poster_config",bo.getPosterConfig());
        activityDO.setContent(JSONUtil.toJsonStr(map));
        return activityMapper.updateById(activityDO) > 0;
    }


    @Override
    public Map getPosterImg(Long activityId, Long memberId,String qrValue) throws Exception{
        Map map = new HashMap();
        ActivityVO activityVO = activityMapper.selectVoById(activityId);
        if (activityVO == null) {
            throw new ServiceException("活动不存在");
        }
        HashMap contentMap = JSONUtil.toBean(activityVO.getContent(), HashMap.class);
        if (contentMap == null) {
            throw new ServiceException("活动内容不存在");
        }
        if (ObjectUtil.isEmpty(Convert.toStr(contentMap.get("poster_config"),null))) {
            throw new ServiceException("活动还未配置海报");
        }
        MemberDetailVO detailVO = memberMapper.selectDetailById(memberId);
        if (detailVO == null) {
            throw new ServiceException("用户信息不存在");
        }
        Map params = new HashMap();
        HashMap posterConfigMap = JSONUtil.toBean(Convert.toStr(contentMap.get("poster_config")), HashMap.class);
        params.put("qrcodeObj",Convert.toStr(posterConfigMap.get("qrBoxObj"),null));
        if (ObjectUtil.isNotEmpty(Convert.toStr(posterConfigMap.get("textBox"),null))) {
            params.put("textBox",Convert.toStr(posterConfigMap.get("textBoxObj"),null));
        }
        if (ObjectUtil.isNotEmpty(Convert.toStr(posterConfigMap.get("headBox"),null)) && ObjectUtil.isNotEmpty(detailVO.getAvatarUrl())) {
            params.put("headBox",Convert.toStr(posterConfigMap.get("headBoxObj"),null));
            params.put("headBoxValue",detailVO.getAvatarUrl());
        }
        if (ObjectUtil.isNotEmpty(Convert.toStr(posterConfigMap.get("nickBox"),null)) && ObjectUtil.isNotEmpty(detailVO.getNickname())) {
            params.put("nickBox",Convert.toStr(posterConfigMap.get("nickBoxObj"),null));
            params.put("nickBoxValue",detailVO.getNickname());
        }

        String qrCreateImg = qrService.createPosterQr(qrValue);
        MultipartFile file = PosterQrcodeUtil.overlapImage(qrCreateImg,Convert.toStr(posterConfigMap.get("bgImg")), params);
        FileVO fileVo = fileService.upload(file.getOriginalFilename(),null, IoUtil.readBytes(file.getInputStream()),null);
        map.put("imgUrl",fileVo.getUrl());
        return map;
    }

    @Override
    public Map getMemberPublicizeUrl(Long memberId, Long activityId) {
        Map map = new HashMap();
        /**
         * 获取分享参数
         */
        MemberDO memberDO = memberMapper.selectById(memberId);
        if (memberDO == null) {
            throw new ServiceException("客户信息不存在");
        }

        /**
         * 获取拼团参数
         */
        LambdaQueryWrapper<OrderDO> orderWrapper = Wrappers.lambdaQuery(OrderDO.class);
        orderWrapper.eq(OrderDO::getMemberId,memberId).eq(OrderDO::getActivityId,activityId).in(OrderDO::getStatus,2,5);
        OrderVO orderVO = orderMapper.selectVoOne(orderWrapper);
        if (orderVO == null) {
            throw new ServiceException("客户不存在可推广信息");
        }

        LambdaQueryWrapper<ShareDO> shareWrapper = Wrappers.lambdaQuery(ShareDO.class);
        shareWrapper.eq(ShareDO::getProductId,activityId).eq(ShareDO::getMemberId,memberId);
        ShareDO shareDO = shareMapper.selectOne(shareWrapper);
        if (shareDO == null) {
            shareDO = new ShareDO();
            shareDO.setMemberId(memberId);
            shareDO.setMemberWxUserId(memberDO.getWxUserId());
            shareDO.setProductId(activityId);
            shareDO.setProductType(1);
            shareDO.setShareNumber(0);
            shareDO.setSpreadNumber(0);
            shareDO.setMemberBuyNumber(0);
            shareDO.setBuyNumber(0);
            shareDO.setPayTotal(BigDecimal.ZERO);
            shareDO.setEnrollStatus(2);//未报名
            shareDO.setUserId(memberDO.getUserId());
            shareMapper.insert(shareDO);
        }
        ShareRecordDO shareRecordDO = new ShareRecordDO();
        shareRecordDO.setShareStaffId(orderVO.getPerformanceStaffId());
        shareRecordDO.setStaffWxUserId(orderVO.getStaffWxUserId());
        shareRecordDO.setShareId(shareDO.getId());
        shareRecordDO.setPassiveMemberId(memberId);
        shareRecordDO.setPassiveMemberWxUserId(memberDO.getWxUserId());
        shareRecordDO.setPreviousShareRecordId(orderVO.getShareRecordId());
        shareRecordDO.setUserId(memberDO.getUserId());
        shareRecordMapper.insert(shareRecordDO);
        String query = "isShare=0&activityId=" + activityId + "&staffId=" + orderVO.getPerformanceStaffId() +
            "&shareId=" + shareDO.getId() + "&shareRecordId=" + shareRecordDO.getId() + "&sharedTeamId=" + orderVO.getGroupPurchaseId();
        /**
         * 获取短链接
         */
        String path = "pages/index/index";
        String urlLink = weChatManager.generateUrlLink(path, query);
        map.put("urlLink",urlLink);
        return map;
    }

    @Override
    public List<ActivityOrderListVO> orderList(ActivityManageDetailParams params) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        params.setUserId(loginUser.getUserId());
        if (params.getEnrollDateRange() != null && params.getEnrollDateRange().size() > 0) {
            params.setEnrollDateRangeStartTime(params.getEnrollDateRange().get(0));
            params.setEnrollDateRangeEndTime(params.getEnrollDateRange().get(1));
        }
        return activityMapper.getOrderList(params);
    }

    @Override
    public TableDataInfo<ActivityVO> settlementPageList(ActivityDO dto, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        LambdaQueryWrapper<ActivityDO> wrapper = Wrappers.lambdaQuery(ActivityDO.class);
        wrapper.like(ObjectUtil.isNotEmpty(dto.getTitle()),ActivityDO::getTitle,dto.getTitle());
        wrapper.eq(ActivityDO::getUserId,loginUser.getUserId());
        wrapper.eq(ActivityDO::getIsDraft,0);
        wrapper.orderByDesc(ActivityDO::getCreateTime);
        Page<ActivityVO> result =  activityMapper.selectVoPage(pageQuery.build(),wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public Map manualSettlement(Long activityId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        Map map = new HashMap();
        ActivityDO activityDO = activityMapper.selectById(activityId);
        if (activityDO == null) {
            throw new ServiceException("活动不存在");
        }
        if (activityDO.getState() != 2) {
            throw new ServiceException("活动未结束，不允许清算！！！");
        }
        map.put("id",activityDO.getId());
        map.put("title",activityDO.getTitle());
        //支付总金额
        map.put("reality_pay_amount_total",0);
        //手续费总金额
        map.put("commission_total",0);
        //一级分销总金额
        map.put("one_distribution_amount_total",0);
        //二级分享总金额
        map.put("two_distribution_amount_total",0);
        //实收总金额
        map.put("actual_amount_total",0);
        List<OrderDO> list = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
            .eq(OrderDO::getActivityId, activityDO.getId())
            .eq(OrderDO::getUserId, loginUser.getUserId())
            .in(OrderDO::getStatus, 2, 5));
        if (list.size() > 0) {
            //支付总金额
            map.put("reality_pay_amount_total",
                list.stream().filter(s -> ObjectUtil.isNotNull(s.getRealityPayAmount())).collect(Collectors.toList())
                    .stream().map(OrderDO::getRealityPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            //手续费总金额
            map.put("commission_total",
                list.stream().filter(s -> ObjectUtil.isNotNull(s.getCommission())).collect(Collectors.toList())
                    .stream().map(OrderDO::getCommission).reduce(BigDecimal.ZERO, BigDecimal::add));
            //一级分销总金额
            map.put("one_distribution_amount_total",
                list.stream().filter(s -> ObjectUtil.isNotNull(s.getOneDistributionAmount())).collect(Collectors.toList())
                    .stream().map(OrderDO::getOneDistributionAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            //二级分享总金额
            map.put("two_distribution_amount_total",
                list.stream().filter(s -> ObjectUtil.isNotNull(s.getTwoDistributionAmount())).collect(Collectors.toList())
                    .stream().map(OrderDO::getTwoDistributionAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            //实收总金额
            map.put("actual_amount_total",
                list.stream().filter(s -> ObjectUtil.isNotNull(s.getActualAmount())).collect(Collectors.toList())
                    .stream().map(OrderDO::getActualAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class,isolation = Isolation.SERIALIZABLE)
    public boolean settlement(Long[] ids) {
        if (ids.length > 0) {
            for (Long activityId : ids) {
                ActivityDO activityDO = activityMapper.selectById(activityId);
                if (activityDO == null) {
                    throw new ServiceException("活动不存在");
                }
                if (activityDO.getState() != 2) {
                    throw new ServiceException("活动未结束，不允许清算！！！");
                }
                SysUser sysUser = baseMapper.selectById(activityDO.getUserId());
                if (sysUser == null) {
                    throw new ServiceException("活动商户不存在");
                }
                activityDO.setSettlementType(2);
                activityMapper.updateById(activityDO);
                List<OrderDO> list = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
                    .eq(OrderDO::getActivityId, activityDO.getId())
                    .eq(OrderDO::getUserId, activityDO.getUserId())
                    .in(OrderDO::getStatus, 2, 5));
                List<OrderDO> waitSet = new ArrayList<>();
                BigDecimal waitSettlementAmount = BigDecimal.ZERO;
                if (list.size() > 0) {
                    for (OrderDO orderDO : list) {
                        /**
                         * 先核销
                         */
                        if (orderDO.getSettlementStatus() == 1) {
                            orderDO.setVerificationTime(DateUtil.getDateTimeString());
                            orderDO.setStatus(5);
                            orderDO.setSettlementStatus(2);
                            orderDO.setVerificationStaffId(-1L);
                            verificationDistribution(orderDO);
                            waitSet.add(orderDO);
                            waitSettlementAmount = waitSettlementAmount.add(orderDO.getActualAmount());
                        }
                    }
                    if (waitSet.size() > 0) {
                        orderMapper.updateBatchById(waitSet);
                    }
                    /**
                     * 清算
                     */
                    sysUser.setWaitSettlementAmount(sysUser.getWaitSettlementAmount().add(waitSettlementAmount));
                    BigDecimal actualAmountTotal = list.stream().filter(s -> ObjectUtil.isNotNull(s.getActualAmount())).collect(Collectors.toList())
                        .stream().map(OrderDO::getActualAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                    sysUser.setWalletAmount(sysUser.getWalletAmount().add(actualAmountTotal));
                    sysUser.setWaitSettlementAmount(sysUser.getWaitSettlementAmount().subtract(actualAmountTotal));
                    baseMapper.updateById(sysUser);
                }
            }
        }
        return true;
    }

    @Override
    public String getStoreName(Long id) {
        String store = "悦商选";
        SysUser sysUser = baseMapper.selectVoById(id);
        if (sysUser != null) {
            store = sysUser.getStoreName();
        }
        return store;
    }

    @Override
    public boolean settlementApply(Long activityId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        SysUser sysUser = baseMapper.selectById(loginUser.getUserId());
        if (sysUser == null) {
            throw new ServiceException("当前用户不存在");
        }
        ActivityDO activityDO = activityMapper.selectById(activityId);
        if (activityDO == null) {
            throw new ServiceException("活动不存在");
        }
        if (activityDO.getState() != 2) {
            throw new ServiceException("活动未结束，不允许清算！！！");
        }
        activityDO.setSettlementType(3);
        return activityMapper.updateById(activityDO) > 0;
    }

    @Override
    public TableDataInfo<ApplySettlementVO> applySettlementPageList(String keyword,ActivityDO dto, PageQuery pageQuery) {
        QueryWrapper<Object> wrapper = Wrappers.query();
        wrapper.eq("ta.state",2);
        if (ObjectUtil.isNotNull(dto.getSettlementType())) {
            wrapper.eq("ta.settlement_type",dto.getSettlementType());
        } else {
            wrapper.in("ta.settlement_type",2,3);
        }
        wrapper.like(ObjectUtil.isNotEmpty(dto.getTitle()),"ta.title",dto.getTitle());
        wrapper.eq(ObjectUtil.isNotNull(dto.getUserId()),"ta.user_id",dto.getUserId());
        wrapper.and(ObjectUtil.isNotEmpty(keyword),wq -> wq.like("su.phonenumber",keyword).or()
            .like("su.user_name",keyword)
        );
        wrapper.orderByDesc("ta.settlement_type");
        Page<ApplySettlementVO> result = activityMapper.applySettlementPageList(pageQuery.build(),wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public List<Map> teamSta(Long id) {
        List<Map> map = activityMapper.teamSta(id);
        return map;
    }

    /**
     * 获取未购买但留下手机号用户
     */
    public Integer getNotPayHaveMobile(Long activityId) {
        Integer number = 0;
        Long count = memberBrowseMapper.selectCount(new LambdaQueryWrapper<MemberBrowseDO>()
            .eq(MemberBrowseDO::getProductId, activityId).eq(MemberBrowseDO::getMemberStatus,1)
            .eq(MemberBrowseDO::getEnrollStatus,2));
        number = Convert.toInt(count,0);
        return number;
    }

    public void getCreateAndNextGroupPurchaseGoodsItem(MemberGroupPurchaseDO memberGroupPurchaseDO) {
        long groupPurchaseGoodsItemId = 0L;
        long nextGroupPurchaseGoodsItemId = 0L;
        /**
         * 阶梯商品列表
         */
        LambdaQueryWrapper<GroupPurchaseGoodsItemDO> goodsItemWrapper = Wrappers.lambdaQuery(GroupPurchaseGoodsItemDO.class);
        goodsItemWrapper.eq(GroupPurchaseGoodsItemDO::getGroupPurchaseGoodsId,memberGroupPurchaseDO.getGroupPurchaseGoodsId())
            .orderByAsc(GroupPurchaseGoodsItemDO::getConstituteNumber);
        List<GroupPurchaseGoodsItemDO> goodsItemDOS = groupPurchaseGoodsItemMapper.selectList(goodsItemWrapper);
        if (goodsItemDOS != null && goodsItemDOS.size() > 0) {
            if (goodsItemDOS.size() == 1) {
                groupPurchaseGoodsItemId = goodsItemDOS.get(0).getId();
                nextGroupPurchaseGoodsItemId = goodsItemDOS.get(0).getId();
            } else {
                for (int i = 0; i < goodsItemDOS.size(); i++) {
                    if (goodsItemDOS.get(i).getConstituteNumber() >= memberGroupPurchaseDO.getPersonnelNumber()) {
                        if (goodsItemDOS.get(i).getConstituteNumber().equals(memberGroupPurchaseDO.getPersonnelNumber())) {
                            groupPurchaseGoodsItemId = goodsItemDOS.get(i).getId();
                        }
                        if (i == goodsItemDOS.size() -1) {
                            nextGroupPurchaseGoodsItemId = goodsItemDOS.get(i).getId();
                        } else {
                            nextGroupPurchaseGoodsItemId = goodsItemDOS.get(i + 1).getId();
                        }
                        break;
                    } else {
                        groupPurchaseGoodsItemId = goodsItemDOS.get(i).getId();
                    }
                }
            }
        }
        if (groupPurchaseGoodsItemId == 0L) {
            memberGroupPurchaseDO.setStatus(1);
        } else if (groupPurchaseGoodsItemId == nextGroupPurchaseGoodsItemId) {
            memberGroupPurchaseDO.setStatus(3);
        } else {
            memberGroupPurchaseDO.setStatus(2);
        }
        memberGroupPurchaseDO.setGroupPurchaseGoodsItemId(groupPurchaseGoodsItemId);
        memberGroupPurchaseDO.setNextGroupPurchaseGoodsItemId(nextGroupPurchaseGoodsItemId);
    }

    /**
     * 清算
     * @param activityId
     */
    @Transactional(rollbackFor = Exception.class,isolation = Isolation.SERIALIZABLE)
    public boolean liquidation(Long activityId) {
        ActivityDO activityDO = activityMapper.selectById(activityId);
        if (activityDO == null) {
            return false;
        }
        if (activityDO.getState() != 2) {
            return false;
        }
        SysUser sysUser = baseMapper.selectById(activityDO.getUserId());
        if (sysUser == null) {
            return false;
        }
        activityDO.setSettlementType(1);
        List<OrderDO> list = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
            .eq(OrderDO::getActivityId, activityDO.getId())
            .eq(OrderDO::getUserId, activityDO.getUserId())
            .in(OrderDO::getStatus, 2, 5));
        List<OrderDO> waitSet = new ArrayList<>();
        BigDecimal waitSettlementAmount = BigDecimal.ZERO;
        if (list.size() > 0) {
            for (OrderDO orderDO : list) {
                /**
                 * 先核销
                 */
                if (orderDO.getSettlementStatus() == 1) {
                    orderDO.setVerificationTime(DateUtil.getDateTimeString());
                    orderDO.setStatus(5);
                    orderDO.setSettlementStatus(2);
                    orderDO.setVerificationStaffId(-1L);
                    verificationDistribution(orderDO);
                    waitSet.add(orderDO);
                    waitSettlementAmount = waitSettlementAmount.add(orderDO.getActualAmount());
                }
            }
            if (waitSet.size() > 0) {
                orderMapper.updateBatchById(waitSet);
            }
            /**
             * 清算
             */
            sysUser.setWaitSettlementAmount(sysUser.getWaitSettlementAmount().add(waitSettlementAmount));
            BigDecimal actualAmountTotal = list.stream().filter(s -> ObjectUtil.isNotNull(s.getActualAmount())).collect(Collectors.toList())
                .stream().map(OrderDO::getActualAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            sysUser.setWalletAmount(sysUser.getWalletAmount().add(actualAmountTotal));
            sysUser.setWaitSettlementAmount(sysUser.getWaitSettlementAmount().subtract(actualAmountTotal));
            baseMapper.updateById(sysUser);
        }
        return activityMapper.updateById(activityDO) > 0;
    }

    /**
     * 定时处理活动状态
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void handleActivityStatus() {
        LambdaQueryWrapper<ActivityDO> wrapper = Wrappers.lambdaQuery(ActivityDO.class);
        wrapper.eq(ActivityDO::getIsDraft,0)
            .eq(ActivityDO::getDeleted,0)
            .ne(ActivityDO::getState,2);
        List<ActivityDO> list = activityMapper.selectList(wrapper);
        if (list.size() > 0) {
            for (ActivityDO activityDO : list) {
                /**
                 * 计算状态
                 */
                long createStamp = DateUtil.getDateline();
                try {
                    long startStamp = DateUtil.getDateline(activityDO.getStartTime(),"yyyy-MM-dd HH:mm:ss");
                    long endStamp = DateUtil.getDateline(activityDO.getEndTime(),"yyyy-MM-dd HH:mm:ss");
                    if (createStamp < startStamp) {
                        activityDO.setState(0);
                    } else if (createStamp >= startStamp && createStamp <= endStamp) {
                        activityDO.setState(1);
                    } else {
                        activityDO.setState(2);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new ServiceException("活动时间不能为空");
                }
            }
            activityMapper.updateBatchById(list);
        }
    }

    /**
     * 定时清算已完成的活动
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void activitySettlement() {
        logger.info("清算定时任务执行开始");
        LambdaQueryWrapper<ActivityDO> wrapper = Wrappers.lambdaQuery(ActivityDO.class);
        wrapper.eq(ActivityDO::getIsDraft,0)
            .eq(ActivityDO::getDeleted,0)
            .eq(ActivityDO::getState,2)
            .in(ActivityDO::getSettlementType,0,3);
        List<ActivityDO> list = activityMapper.selectList(wrapper);
        if (list.size() > 0) {
            for (ActivityDO activityDO : list) {
                int diffMinutes = DateUtil.getDiffMinutes(activityDO.getEndTime(), DateUtil.getDateTimeString());
                if (diffMinutes / (24 * 60) >= 3) {
                    this.liquidation(activityDO.getId());
                }
            }
        }
        logger.info("清算定时任务执行结束");
    }

    /**
     * 核销的分销明细
     * @param orderDO
     */
    private void verificationDistribution(OrderDO orderDO){
        /**
         * 处理明细记录
         */
        List<OrderTradeRecordDO> tradeRecordList = new ArrayList<>();

        /**
         * 删除待结算的订单交易记录
         */
        orderTradeRecordMapper.delete(new LambdaQueryWrapper<OrderTradeRecordDO>()
            .eq(OrderTradeRecordDO::getOrderId,orderDO.getId()).eq(OrderTradeRecordDO::getSettlementStatus,1));

        // 收入-全额
        OrderTradeRecordDO amountTradeRecord = new OrderTradeRecordDO();
        amountTradeRecord.setOrderId(orderDO.getId());
        amountTradeRecord.setFundType("order_settled");
        amountTradeRecord.setTradeAmount(orderDO.getRealityPayAmount());
        amountTradeRecord.setMemberId(orderDO.getMemberId());
        amountTradeRecord.setMemberWxUserId(orderDO.getMemberWxUserId());
        amountTradeRecord.setSettlementStatus(2);
        amountTradeRecord.setUserId(orderDO.getUserId());
        tradeRecordList.add(amountTradeRecord);
        // 手续费
        OrderTradeRecordDO commissionTradeRecord = new OrderTradeRecordDO();
        commissionTradeRecord.setOrderId(orderDO.getId());
        commissionTradeRecord.setFundType("charge_deduction");
        commissionTradeRecord.setTradeAmount(orderDO.getCommission().negate());
        commissionTradeRecord.setMemberId(orderDO.getMemberId());
        commissionTradeRecord.setMemberWxUserId(orderDO.getMemberWxUserId());
        commissionTradeRecord.setSettlementStatus(2);
        commissionTradeRecord.setUserId(orderDO.getUserId());
        tradeRecordList.add(commissionTradeRecord);
        // 分销佣金（一级）
        Long twoShareRecordId =0L;
        //查询分享记录
        if (orderDO.getOneDistributionAmount() != null && orderDO.getOneDistributionAmount().compareTo(BigDecimal.ZERO) == 1) {
            OrderTradeRecordDO oneDistributionTradeRecord = new OrderTradeRecordDO();
            oneDistributionTradeRecord.setOrderId(orderDO.getId());
            oneDistributionTradeRecord.setFundType("invite_deduction");
            oneDistributionTradeRecord.setTradeAmount(orderDO.getOneDistributionAmount().negate());
            oneDistributionTradeRecord.setMemberId(orderDO.getMemberId());
            oneDistributionTradeRecord.setMemberWxUserId(orderDO.getMemberWxUserId());
            oneDistributionTradeRecord.setSettlementStatus(2);
            oneDistributionTradeRecord.setUserId(orderDO.getUserId());
            tradeRecordList.add(oneDistributionTradeRecord);
        }
        // 分销佣金（二级）
        if (orderDO.getTwoDistributionAmount() != null && orderDO.getTwoDistributionAmount().compareTo(BigDecimal.ZERO) == 1) {
            OrderTradeRecordDO twoDistributionTradeRecord = new OrderTradeRecordDO();
            twoDistributionTradeRecord.setOrderId(orderDO.getId());
            twoDistributionTradeRecord.setFundType("invite_deduction");
            twoDistributionTradeRecord.setTradeAmount(orderDO.getTwoDistributionAmount().negate());
            twoDistributionTradeRecord.setMemberId(orderDO.getMemberId());
            twoDistributionTradeRecord.setMemberWxUserId(orderDO.getMemberWxUserId());
            twoDistributionTradeRecord.setSettlementStatus(2);
            twoDistributionTradeRecord.setUserId(orderDO.getUserId());
            tradeRecordList.add(twoDistributionTradeRecord);
        }
        orderTradeRecordMapper.insertBatch(tradeRecordList);
    }
}
